/******************************************************************************

@File         : wavdemo.c
@Author       : Conor Mac Aoidh, conormacaoidh@gmail.com
@Brief        : Used for testing the realtime sonant synth
Date          : 28/06/2012

This demo file runs the Realtime Sonant Synth. Usage:

./wavdemo[.exe] N

Where N is the number of buffers you wish to render (the size of
the render buffer is set with BUFF_SIZE in sonant.h)

This file emulates a realtime application by generating the audio
in realtime and saving the result to a wav file for playback.

The song being synthesised is contained in a header file generated
by the Sonant Synth (http://www.pouet.net/prod.php?which=53615) and
included in sonant.c

******************************************************************************/

/******************************************************************************
	1: Include files
******************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include "includes/WavLib.h"
#include "sonant.h"

/******************************************************************************
	4: Functions Implementation
******************************************************************************/

// uses WavLib.c to write the buffer to a wav file for testing/demo purposes
void write_wavfile(short* wave_buffer, char *filename, unsigned int size) {
	#ifdef DEBUG
		printf("writing %s file\n", filename);
	#endif

	WAVInfo_t  WaveFile;
	WaveFile = WAV_New(16,2,44100);
	WAV_SetData( WaveFile, wave_buffer, size);
	WAV_Write( WaveFile, filename );

}

// ./demo.c N
// where N is the number of buffers you wish to generate
int main( int argc, char *argv[ ] ){

	// allocate memory in heap
	int i, run = ( argc == 1 ) ? 1 : atoi( argv[ 1 ] );
	short* left_buffer = ( short* ) malloc( sizeof( short ) * BUFF_SIZE );
	short* right_buffer = ( short* ) malloc( sizeof( short ) * BUFF_SIZE );
	short* master_buffer = ( short* ) malloc( sizeof( short ) * BUFF_SIZE * 2 * run );

	// sets up the sonant (performs various optimization calculations)
	Sonant_init( );

	// generate samples
	for( i = 0; i < run; ++i ){
		#ifdef DEBUG
				printf( "\nmain( ): running sonant %d\n\n", i );
		#endif
		Sonant_render( left_buffer, right_buffer );

		// copy render data to master buffer
		Sonant_merge( ( master_buffer + ( BUFF_SIZE * i ) ), left_buffer, right_buffer );
	}

	// write samples to wavfile using WavLib
	write_wavfile( master_buffer, (char*) "sonant.wav", (unsigned int) BUFF_SIZE * run );

	return 0;
}

/******************************************************************************
	End of file
******************************************************************************/
